package com.objectechenica.java.net;

import java.io.IOException;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

import com.objectechenica.java.ui.DownloadListener;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.component.Dialog;

public class ImageDownloader extends NetRequest implements Runnable {
	// Holds the URL to download the image
	StringBuffer url = null;
	
	//holds the instance of the delegate screen
	protected Object delegate;
	
	public ImageDownloader(String url) {
		// image URL 
		this.url = new StringBuffer();
		this.url.append(url.toString());
	}
	
	//taking the instance of the delegate
	//this is the object of the active screen from where the request is made
	public Object getDelegate() {
		return delegate;
	}

	public void setDelegate(Object delegate) {
		this.delegate = delegate;
	}
	    
	// Thread starts the execution
	public void run() {
		byte[] dataArray;
		InputStream input;	
		url.append(updateConnSuffix());

		HttpConnection httpConn = null;
		try {
			httpConn = (HttpConnection) Connector.open(url.toString());

			input = httpConn.openInputStream();

			dataArray = net.rim.device.api.io.IOUtilities.streamToBytes(input);

			final Bitmap googleImage = Bitmap.createBitmapFromBytes( dataArray, 0, -1, 1);
			
			((DownloadListener) delegate).downloadSuccess(googleImage);

		} catch (IOException e) {
			e.printStackTrace();
			Dialog.alert("Eoor in downloading image");
		}		
	}	
}